package com.qf.servlet;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Ypl
 * @version V1.0
 * @Project September-mavens
 * @Package com.qf.servlet
 * @Description:
 * @Date 2022/10/12 19:24
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/admin/auth")
//@CrossOrigin("http://localhost")
public class AdminAuthController {
    @Autowired
    DtsRoleService dtsRoleService;

    @Autowired
    DtsPermissionService dtsPermissionService;


    /**
     * 获取验证码
     */

    @RequestMapping("/captchaImage")
    public Object captchaImage() throws IOException {
//        生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(2);
//        生成uuid
        String uuid = UUID.randomUUID().toString();
//        在缓存区存储验证码,
        CaptchaCodeManager.addToCache(uuid,code,10);
//        获取输出流对象
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        //输出图片
        VerifyCodeUtils.outputImage(110, 35,byteArrayOutputStream,code);

//        对应前端需求的接受参数
        Map<String,Object> data = new HashMap<>();

        data.put("img", Base64.encode(byteArrayOutputStream.toByteArray()));
        data.put("uuid",uuid);
        return ResponseUtil.ok(data);
    }

    /**
     * 认证
     */
    @RequestMapping("/login")
    public Object login(@RequestBody Map<String,String> map, HttpSession session){

        String code = map.get("code");
        String password = map.get("password");
        String username = map.get("username");
        String uuid = map.get("uuid");

        if(StringUtils.isEmpty(code)||StringUtils.isEmpty(password)||
                StringUtils.isEmpty(username)||StringUtils.isEmpty(uuid)){
            return ResponseUtil.badArgument();
        }
        //校验验证码
        //获取缓存中的验证码

        CaptchaCodeManager captchaCodeManager = new CaptchaCodeManager();
        String captcha = captchaCodeManager.getCachedCaptcha(uuid);

        if(!code.equalsIgnoreCase(captcha)){
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }

        //认证
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, "未知的账户");
        } catch (LockedAccountException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, "账户已锁定");
        } catch (CredentialsException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, "密码错误");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, "认证错误");
        }

        String data = session.getId();

        return ResponseUtil.ok(data);

    }

    /**
     * 获取用户的信息
     */
    @RequestMapping("/info")
    public Object info(){
//        获取session
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();

        //根据用户查询用户的角色和权限
        Set<String> roles = dtsRoleService.findRoleByIds(admin.getRoleIds());
        Set<String> psm = dtsPermissionService.finfPsmByIds(admin.getRoleIds());

        Map<String,Object> map = new HashMap<>();

        map.put("roles",roles);
        map.put("name",admin.getUsername());
        map.put("perms",psm);
        map.put("avatar",admin.getAvatar());

        return ResponseUtil.ok(map);
    }
}
